package cn.edu.zjicm.wordsnet_d.view;

import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.data.OneWord;
import cn.edu.zjicm.wordsnet_d.media.VoicePlayer;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import cn.edu.zjicm.wordsnet_d.util.NightModeUtil;
import cn.edu.zjicm.wordsnet_d.util.TypefaceUtil;
import cn.edu.zjicm.wordsnet_d.util.Utils;

public class WriteView extends LinearLayout {

	private Context mContext;
	private int mCurrentIndex;
	private OneWord oneWord;
	private TextView mCnText;
	private TextView mPhoneticText;
	private FlowLayout mFlowLayoutDisplay;
	private FlowLayout mFlowLayoutClick;
	private TextView[] mBlanks;
	private ImageView mRightOrWrongIcn;
	private TextView pressForPrompt;
	private String[] wordSyllablesRight;
	private int wordsPadding;
	private int underLine;
	private int textColorNormal;

	public WriteView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		wordsPadding = Utils.changeDipToPx(mContext, 10);
	}

	public WriteView(Context context) {
		this(context, null);
	}

	@Override
	protected void onFinishInflate() {
		super.onFinishInflate();
		mCnText = (TextView) findViewById(R.id.write_word_cn);
		mPhoneticText = (TextView) findViewById(R.id.write_word_phonetic2);
		TypefaceUtil.getInstance(mContext).setTypeface(mPhoneticText);// 设置音标字体
		mFlowLayoutDisplay = (FlowLayout) findViewById(R.id.spell_write_word_container);
		mFlowLayoutClick = (FlowLayout) findViewById(R.id.spell_write_letter_container);
		mRightOrWrongIcn = (ImageView) findViewById(R.id.write_right_or_wrong_icn);
		pressForPrompt = (TextView) findViewById(R.id.prompt);// 提示按钮
	}

	public void init(OneWord oneword) {
		this.oneWord = oneword;
		if (NightModeUtil.isNightModeNow()) {
			underLine = R.drawable.underline_night;
			textColorNormal = R.color.word_color_night;
		} else {
			underLine = R.drawable.underline;
			textColorNormal = R.color.write_normal_color;
		}
		mCnText.setText(oneWord.getSensesSenior());
		initWriteViews();
	}

	/**
	 * 再写一遍，重写 重新构建抄写
	 */
	public void reWrite() {
		playOneWordVoice();
		initWriteViews();
		pressForPrompt.setVisibility(View.GONE);
	}

	public void playOneWordVoice() {
		VoicePlayer.getInstance(mContext).play(oneWord);
	}

	public String hint() {
		String s = oneWord.getLemma();
		return s;
	}

	private void initWriteViews() {
		if (!isToShowKeyBoard()) {
			mFlowLayoutClick.setVisibility(View.VISIBLE);
			initWriteViewByButton();
		} else {
			mFlowLayoutClick.setVisibility(View.INVISIBLE);
			initWriteViewByKeyBoard();
		}
	}

	public boolean isToShowKeyBoard() {
		if (oneWord.getSyllableCount() > 1)
			return false;
		else
			return true;
	}

	int currentIndexForKeyBoard = 0;
	EditText[] editTextList;

	private void initWriteViewByKeyBoard() {
		mFlowLayoutDisplay.removeAllViews();
		String word = oneWord.getLemma();
		currentIndexForKeyBoard = 0;

		editTextList = new EditText[word.length()];

		for (int i = 0; i < editTextList.length; i++) {
			editTextList[i] = new EditText(mContext);
			editTextList[i].setBackgroundResource(underLine);
			editTextList[i].setMinWidth(Utils.changeDipToPx(mContext, 15));
			editTextList[i].setTextSize(27);
			editTextList[i].setCursorVisible(false);
			editTextList[i].setClickable(false);
			editTextList[i].setFocusable(false);
			editTextList[i].setFocusableInTouchMode(false);
			editTextList[i].setGravity(Gravity.CENTER_HORIZONTAL);
			editTextList[i].setTextColor(getResources().getColor(textColorNormal));
			editTextList[i].setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
			editTextList[i].setOnKeyListener(new OnKeyListener() {
				@Override
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					if ((KeyEvent.ACTION_UP == event.getAction()) && keyCode == KeyEvent.KEYCODE_DEL) {
						if ((currentIndexForKeyBoard == editTextList.length - 1)
								&& (!(1 + "").equals(editTextList[currentIndexForKeyBoard].getTag()))) {
							editTextList[currentIndexForKeyBoard].setFocusable(true);
							editTextList[currentIndexForKeyBoard].setFocusableInTouchMode(true);
							editTextList[currentIndexForKeyBoard].setText("");
							editTextList[currentIndexForKeyBoard].setTag(1 + "");
							editTextList[currentIndexForKeyBoard].requestFocus();
							mRightOrWrongIcn.setVisibility(View.GONE);
							changeTextColorToNormal();
						} else if (currentIndexForKeyBoard > 0) {
							editTextList[currentIndexForKeyBoard].setFocusable(false);
							editTextList[currentIndexForKeyBoard].setFocusableInTouchMode(false);
							currentIndexForKeyBoard--;
							editTextList[currentIndexForKeyBoard].setFocusable(true);
							editTextList[currentIndexForKeyBoard].setFocusableInTouchMode(true);
							editTextList[currentIndexForKeyBoard].requestFocus();
							editTextList[currentIndexForKeyBoard].setText("");
						}
					}
					return false;
				}
			});

			editTextList[i].addTextChangedListener(new TextWatcher() {
				String strBefore = "";

				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
					if (s.length() > 1) {
						editTextList[currentIndexForKeyBoard].setText(strBefore);
					} else if (s.length() > 0) {
						if (currentIndexForKeyBoard < editTextList.length - 1) {
							editTextList[currentIndexForKeyBoard].setFocusable(false);
							editTextList[currentIndexForKeyBoard].setFocusableInTouchMode(false);
							currentIndexForKeyBoard++;
							editTextList[currentIndexForKeyBoard].setFocusable(true);
							editTextList[currentIndexForKeyBoard].setFocusableInTouchMode(true);
							editTextList[currentIndexForKeyBoard].requestFocus();
						} else {
							// editTextList[currentIndexForKeyBoard].setFocusable(false);
							// editTextList[currentIndexForKeyBoard].setFocusableInTouchMode(false);
							checkAnswerForKeyBoard();
							editTextList[currentIndexForKeyBoard].setTag(0);
							editTextList[currentIndexForKeyBoard].setFocusable(true);
							editTextList[currentIndexForKeyBoard].setFocusableInTouchMode(true);
							editTextList[currentIndexForKeyBoard].requestFocus();
						}
					}
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start, int count, int after) {
					strBefore = s + "";
				}

				@Override
				public void afterTextChanged(Editable s) {

				}
			});
			mFlowLayoutDisplay.addView(editTextList[i]);
		}
		editTextList[0].setFocusable(true);
		editTextList[0].setFocusableInTouchMode(true);
		editTextList[0].requestFocus();
		mPhoneticText.setVisibility(View.INVISIBLE);
		mRightOrWrongIcn.setVisibility(View.GONE);
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			public void run() {
				InputMethodManager inputManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
				inputManager.showSoftInput(editTextList[0], InputType.TYPE_NULL);
			}

		}, 200);
	}

	private void initWriteViewByButton() {
		if (TextUtils.isEmpty(oneWord.getLemma()))
			return;
		mFlowLayoutDisplay.removeAllViews();
		mFlowLayoutClick.removeAllViews();

		mPhoneticText.setVisibility(View.INVISIBLE);
		mRightOrWrongIcn.setVisibility(View.GONE);
		mCurrentIndex = 0;
		btnClickedOld = null;

		wordSyllablesRight = oneWord.getSyllables();
		List<String> disturbSyllables = oneWord.getDisturbSyllables();
		String[] disturbSyllablesStrs = new String[disturbSyllables.size()];
		for (int i = 0; i < disturbSyllables.size(); i++) {
			disturbSyllablesStrs[i] = disturbSyllables.get(i);
		}
		// wordSyllables = wordSyllablesTemp + disturbSyllablesStrs;
		String[] wordSyllables = new String[wordSyllablesRight.length + disturbSyllablesStrs.length];
		System.arraycopy(wordSyllablesRight, 0, wordSyllables, 0, wordSyllablesRight.length);
		System.arraycopy(disturbSyllablesStrs, 0, wordSyllables, wordSyllablesRight.length, disturbSyllablesStrs.length);
		Arrays.sort(wordSyllables);

		mBlanks = new TextView[wordSyllables.length];
		for (int i = 0; i < wordSyllables.length; i++) {
			if (i < wordSyllablesRight.length) {
				TextView buttonToDisplayView = new TextView(mContext);

				buttonToDisplayView.setBackgroundResource(R.drawable.underline);
				buttonToDisplayView.setMinWidth(Utils.changeDipToPx(mContext, 30));
				buttonToDisplayView.setTextSize(27);
				buttonToDisplayView.setGravity(Gravity.CENTER_HORIZONTAL);
				buttonToDisplayView.setTextColor(getResources().getColor(R.color.write_right_color));
				mFlowLayoutDisplay.addView(buttonToDisplayView);
			}
			TextView buttonToClickView = new TextView(mContext);
			buttonToClickView.setText(wordSyllables[i]);
			setBtnOrigin(buttonToClickView);
			buttonToClickView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					setClickedOldOrigin();
					if (isClickedRight((TextView) v)) {
						v.setVisibility(View.INVISIBLE);
						TextView tv = (TextView) (mFlowLayoutDisplay.getChildAt(mCurrentIndex));
						tv.setText(((TextView) v).getText());
						tv.setMinWidth(0);
						mCurrentIndex++;
						checkIsSpellFinishedForClicked();
					} else {
						setBtnRed((TextView) v);
					}
				}
			});
			mFlowLayoutClick.addView(buttonToClickView);
		}
	}

	private void checkIsSpellFinishedForClicked() {
		if (mCurrentIndex >= wordSyllablesRight.length) {
			mPhoneticText.setVisibility(View.VISIBLE);
			mFlowLayoutClick.setVisibility(View.INVISIBLE);
			mPhoneticText.setText(oneWord.getPhonetic());
			mRightOrWrongIcn.setImageResource(R.drawable.right_ico);
			mRightOrWrongIcn.setVisibility(View.VISIBLE);
			for (int i = 0; i < mFlowLayoutDisplay.getChildCount(); i++) {
				int color;
				if (i % 2 == 0) {
					color = R.color.text_color_for_syllable_green;
				} else {
					color = R.color.text_color_for_syllable_red;
				}
				TextView tv = (TextView) mFlowLayoutDisplay.getChildAt(i);
				tv.setTextColor(getResources().getColor(color));
				tv.setBackgroundColor(Color.TRANSPARENT);
			}
			playOneWordVoice();
		}
	}

	private void checkAnswerForKeyBoard() {
		boolean isRight = true;
		String word = oneWord.getLemma();
		for (int i = 0; i < editTextList.length; i++) {
			editTextList[i].setFocusable(false);
			String str = editTextList[i].getText().toString();
			if (str.length() > 0) {
				char c = str.charAt(0);
				char rightChar = word.charAt(i);
				if (rightChar != c) {
					isRight = false;
					editTextList[i].setTextColor(getResources().getColor(R.color.write_wrong_color));
					mRightOrWrongIcn.setImageResource(R.drawable.wrong_ico);
					mRightOrWrongIcn.setVisibility(View.VISIBLE);
				} else {
					editTextList[i].setTextColor(getResources().getColor(R.color.write_right_color));
				}
			}
		}
		if (isRight) {
			mRightOrWrongIcn.setImageResource(R.drawable.right_ico);
			mRightOrWrongIcn.setVisibility(View.VISIBLE);
			playOneWordVoice();
		}
		mPhoneticText.setVisibility(View.VISIBLE);
		mPhoneticText.setText(oneWord.getPhonetic());
		// InputMethodManager inputManager = (InputMethodManager)
		// getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
		// inputManager.hideSoftInputFromWindow(getWindowToken(),
		// InputType.TYPE_NULL);
	}

	private void changeTextColorToNormal() {
		for (int i = 0; i < editTextList.length; i++) {
			editTextList[i].setTextColor(getResources().getColor(textColorNormal));
		}
	}

	private void setBtnOrigin(TextView btn) {
		btn.setBackgroundResource(R.drawable.spell_white_selector);
		btn.setTextColor(getResources().getColor(R.color.black));
		btn.setTextSize(20);
		btn.setPadding(wordsPadding, wordsPadding, wordsPadding, wordsPadding);
	}

	TextView btnClickedOld;

	private void setClickedOldOrigin() {
		if (btnClickedOld != null) {
			setBtnOrigin(btnClickedOld);
		}
	}

	private void setBtnRed(TextView btn) {
		btn.setBackgroundResource(R.drawable.spell_red);
		btn.setTextColor(getResources().getColor(R.color.white));
		btn.setPadding(wordsPadding, wordsPadding, wordsPadding, wordsPadding);
		btnClickedOld = btn;
	}

	private boolean isClickedRight(TextView tv) {
		boolean isRight = false;
		String str = tv.getText().toString();
		if (str.equals(wordSyllablesRight[mCurrentIndex])) {
			isRight = true;
		}
		return isRight;
	}
}
